package com.netkiller.mailmonitor.workflow.impl.task;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Logger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.netkiller.mailmonitor.core.APP_CONSTANTS;
import com.netkiller.mailmonitor.entity.AppUser;
import com.netkiller.mailmonitor.entity.LogMessage;
import com.netkiller.mailmonitor.entity.OAuthEntity;
import com.netkiller.mailmonitor.service.AppUserService;
import com.netkiller.mailmonitor.service.ContextIOService;
import com.netkiller.mailmonitor.service.LogMessageService;
import com.netkiller.mailmonitor.service.OauthService;
import com.netkiller.mailmonitor.util.UserUtil;
import com.netkiller.mailmonitor.vo.AppProperties;
import com.netkiller.mailmonitor.workflow.AbstractWorkflowTask;
import com.netkiller.mailmonitor.workflow.WorkflowContext;
import com.netkiller.mailmonitor.workflow.WorkflowExecutionException;
import com.netkiller.mailmonitor.workflow.impl.context.AuthorizeContextIOForAllDomainUsersContext;

public class AuthorizeContextIOForAllDomainUsersTask extends
		AbstractWorkflowTask {

	protected final Logger logger = Logger.getLogger(getClass().getName());

	@Autowired
	private AppProperties appProperties;
	
	@Autowired private LogMessageService logMessageService;

	@Autowired
	OauthService oauthService;

	@Autowired
	AppUserService appUserService;

	@Autowired
	private ContextIOService contextIOService;
	
	//@Autowired private WorkflowService workflowService;
	
	public static int runs = 0;
	
	public static Long lastRun =0L;
	public static String lastUserEmail = "";

	@Override
	public WorkflowContext execute(WorkflowContext context)
			throws WorkflowExecutionException {
		System.out.println("starting task");
		LogMessage logMessage = new LogMessage();
		AuthorizeContextIOForAllDomainUsersContext thisContext = (AuthorizeContextIOForAllDomainUsersContext) context;
		String email = thisContext.getAdminEmail();
		Long now = new Date().getTime();
		Long difference = (now - lastRun)/1000;
		if ((difference>= APP_CONSTANTS.TIME_LIMIT)) {
			lastRun = now;
			lastUserEmail = email;
			try {				
				//String domain = UserUtil.getDomain(email);
				//List<String> users = appUserService.getAllDomainUsers(domain);
				List<AppUser>  appUsers= appUserService.getAllUsers();
				addImapAccountForUsers(appUsers, email);
				logMessage.setMessage("All Users Synced");
			} catch (Exception e) {
				logMessage.setMessage("User Sync Failed");
				System.out.println("Error occurred : " + e.getMessage());
			}
		}
		logMessageService.save(logMessage);
		System.out.println("task finished. No. of runs :" + ++runs);
		return context;
	}

	private void addImapAccountForUsers(List<AppUser>  appUsers, String adminEmail) {
		Date toDate = new Date();
		Date  fromDate = new Date(toDate.getTime() + 3600000);
		for (AppUser appUser : appUsers) {
			String	user = appUser.getEmail();
			String response = contextIOService.fetchMailsByUser(user, fromDate,
					toDate);
				if (response.equalsIgnoreCase("[error]")){
							System.out
									.println(user + " account or sources do not exist ");
							String resp = createAccount(adminEmail, appUser);
							//System.out.println(resp);
				} else {
					System.out.println(user + " is synced");
				}

		}
		

	}

	private String createAccount(String adminEmail, AppUser appUser) {
		String reply = "Mail sent asking for authorization to "+ appUser.getEmail() ;
		OAuthEntity oAuthEntity = oauthService.getRequestToken(appUser.getEmail());
		if (oAuthEntity != null) {
			
			String approvalUrl = oAuthEntity.getAuthorizationUrl();
			String oauthToken = oAuthEntity.getKey();
			String oauthSecret = oAuthEntity.getSecret();
			appUser.setOauthtokensecret(oauthSecret);
			appUser.setOauthtoken(oauthToken);
			appUserService.save(appUser);
			appUserService.sendApprovalMailToUser(appProperties.getUsername(),adminEmail,appUser.getEmail(), approvalUrl);
			System.out.println("approval Url : " + approvalUrl);
		} else {
			System.out.println("oauthParameters is null");
		}
		return reply;
	}
	



	

}
